package com.ls.lsojcodesandbox.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.ls.lsojcodesandbox.CodeSandbox;
import com.ls.lsojcodesandbox.model.ExecuteCodeRequest;
import com.ls.lsojcodesandbox.model.ExecuteCodeResponse;
import com.ls.lsojcodesandbox.model.ExecuteMessage;
import com.ls.lsojcodesandbox.model.JudgeInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.jni.Time;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.UUID;

@Slf4j
public class JavaCodeSandboxTemplate implements CodeSandbox {

    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";
    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";
    private static final long TIME_OUT = 5000;

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();
        //1.保存代码
        File userCodeFile = SaveToFile(code);

        File parentFile = userCodeFile.getParentFile();
        String lastFileName = FileUtil.getName(parentFile);

        //2.编译代码
        ExecuteMessage executeMessage = compileFile(userCodeFile);

        //3.使用代码沙箱执行代码
        List<ExecuteMessage> executeMessages = runFile(userCodeFile, inputList, lastFileName);

        //4.收集结果
        ExecuteCodeResponse outputResponse = getOutputResponse(executeMessages);

        //5.销毁临时文件
        Boolean b = deleteFile(userCodeFile);
        if(!b) {
            log.error("deleteFile error + {}", userCodeFile.getAbsolutePath());
        }
        return outputResponse;
    }

    /**
     * 将用户的代码保存为文件编译编译和执行
     * @param code
     * @return
     */
    public File SaveToFile(String code) {
        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        //1.创建文件夹
        if(!FileUtil.exist(globalCodePathName)){
            FileUtil.mkdir(globalCodePathName);
        }
        //将用户的代码隔离存放
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        return userCodeFile;
    }

    /**
     * 编译文件
     * @param userCodeFile
     * @return
     */
    public ExecuteMessage compileFile(File userCodeFile) {
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());
        Runtime runtime = Runtime.getRuntime();
        try {
            Process compileProcess = runtime.exec(compileCmd);
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
            if(executeMessage.getExitValue()!=0) {
                throw new RuntimeException("编译错误");
            }
            return executeMessage;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 执行输入用例
     * @param userCodeFile
     * @param inputList
     * @return
     */
    public List<ExecuteMessage> runFile(File userCodeFile, List<String> inputList, String lastFileName) {
        String userCodePath = userCodeFile.getParentFile().getAbsolutePath();
        List<ExecuteMessage> executeMessageLists = new ArrayList<>();
        for(String input : inputList) {
            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s", userCodePath, input);
            try {
                Process process = Runtime.getRuntime().exec(runCmd);
                //超时控制
                new Thread(()->{
                    try {
                        Thread.sleep(TIME_OUT);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println("超时了，强行中断");
                    process.destroy();
                }).start();
                ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(process, "执行");
                executeMessageLists.add(executeMessage);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return executeMessageLists;
    }

    /**
     * 汇总输出结果并封装成 ExecuteCodeResponse
     * @param executeMessages
     * @return
     */
    public ExecuteCodeResponse getOutputResponse(List<ExecuteMessage> executeMessages) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputLists = new ArrayList<>();
        long maxTime = 0L;
        long maxMemory = 0L;
        for(ExecuteMessage executeMessage : executeMessages) {
            String errorMessage = executeMessage.getErrorMessage();
            if(StrUtil.isNotBlank(errorMessage)) {
                executeCodeResponse.setStatus(3);
                executeCodeResponse.setMessage(errorMessage);
                break;
            }
            if(executeMessage.getTime()!=null) {
                maxTime = Math.max(maxTime, executeMessage.getTime());
            }
            if(executeMessage.getMemory()!=null) {
                maxMemory = Math.max(maxMemory, executeMessage.getMemory());
            }
            outputLists.add(executeMessage.getMessage());
        }
        if(executeMessages.size()==outputLists.size()) {
            executeCodeResponse.setStatus(0);
        }
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setOutputList(outputLists);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
        judgeInfo.setMemory(maxMemory);
        executeCodeResponse.setJudgeInfo(judgeInfo);
        return executeCodeResponse;
    }

    /**
     * 删除文件
     * @param userCodeFile
     * @return
     */
    public Boolean deleteFile(File userCodeFile) {
        String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();
        boolean del = FileUtil.del(userCodeParentPath);
        System.out.println(del ? "删除成功" : "删除失败");
        return del;
    }
}
